#include "tcpserverinit.h"
int tcpserver_init(int port)
{
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if(sockfd < 0)
	{
		perror("socket fail");
		return -1;
	}
	
	//地址复用
	int on=1;
	int ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
	

	//绑定
	struct sockaddr_in svraddr;
	memset(&svraddr, 0, sizeof(svraddr));
	svraddr.sin_family = AF_INET;
	svraddr.sin_port = htons(port);
	svraddr.sin_addr.s_addr = htonl(INADDR_ANY);

	ret = bind(sockfd, (struct sockaddr*)&svraddr, sizeof(svraddr));
	if(ret < 0)
	{
		perror("bind fail");
		close(sockfd);
		return -1;
	}

	//监听
	ret = listen(sockfd, 10);
	if(ret < 0)
	{
		
		perror("bind fail");
		close(sockfd);
		return -1;
	}
	return sockfd;
}
